package com.example.cafe.work.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

import com.example.cafe.work.dto.UserSenstive;
import com.example.cafe.work.util.UserHolder;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.cafe.work.util.RedisConstants.LOGIN_USER_KEY;
import static com.example.cafe.work.util.RedisConstants.LOGIN_USER_TTL;


public class RefreshTokenInterceptor implements HandlerInterceptor {

    //如果想要在拦截器中使用StringRedisTemplate，不能直接注入
    private  StringRedisTemplate stringRedisTemplate;
    //通过创建一个构造方法，将来在config配置类中，去添加RefreshTokenInterceptor对象的时候
    //需要传递一个RefreshTokenInterceptor对象
    //创建RefreshTokenInterceptor对象，就必须要传递stringRedisTemplate这个参数
    //可以拿一个spring中注入好的stringRedisTemplate传进来使用
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1,先判断请求token是否携带了
        String token = request.getHeader("authorization");
        System.out.println(token);
        if (StrUtil.isBlank(token)){
            return true;
        }
        //获取redis中的用户信息
        String key = LOGIN_USER_KEY + token;
        System.out.println(key);
        //通过key，获取redis存放的用户对象
        HashOperations<String, Object, Object> hashRedis =
                stringRedisTemplate.opsForHash();
        Map<Object, Object> userMap = hashRedis.entries(key);
        System.out.println("花"+userMap);
        //2,判断用户是否存在
        if (userMap.isEmpty()){
            return true;
        }
        //3,存在，保存用户信息到ThreadLocal中
        //先把userMap转为UserDTO对象
        UserSenstive userDTO = BeanUtil.
                fillBeanWithMap(userMap, new UserSenstive(), false);
        UserHolder.saveUser(userDTO);
        //刷新有效期
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //4,放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //把ThreadLocal中的用户信息移除掉
        UserHolder.removeUser();
    }
}
